package com.fingard.dsp.bank.directbank.zyb02;

import com.dcfs.esc.ftp.client.FtpClientConfig;
import com.dcfs.esc.ftp.client.upload.FtpPut;
import com.dcfs.esc.ftp.client.download.FtpGet;
import com.dcfs.esc.ftp.client.upload.FtpPutStream;

public class WgetUtil {

    private static final int  timeout = 5000;
    //wget命令举例如下
    //wget -d -o /home/zyb/test.log -O /home/zyb/test.txt http://10.102.55.2/uat8_zjy/batch/down/4100000031_29724130_20240101.txt
    public static int getFile(String logFile, String localFile, String remoateFile, StringBuilder errMsg) {
        Runtime runtime = Runtime.getRuntime();
        String mainCmd = "wget -d -o " + logFile + " -O " + localFile + " " + remoateFile;
        try {
            Process mainPrc = runtime.exec(mainCmd);
            return mainPrc.waitFor();//正常返回0
        } catch (Exception e) {
            errMsg.append(e.getMessage());
        }
        return -1;
    }

    /**
     * 从文件传输平台下载文件
     *
     * @param remoteFileName 文件传输系统文件路径
     * @param localFileName  本地文件路径
     * @param transCode      传输交易码
     * @param errMsg
     * @param config
     * @return 文件是否下载成功
     */
    public static int downLoadFile(String remoteFileName, String localFileName, String transCode, StringBuilder errMsg,
                                   FtpClientConfig config) {
        FtpGet ftpGet = new FtpGet(remoteFileName, localFileName, transCode, config);
        try {
            if (ftpGet.doGetFile() == true) {
                return 0;
            }
        } catch (Exception e) {
            errMsg.append(e.getMessage());
        }
        return -1;
    }


    /**
     * 通过流的方式上传文件
     * @param lcoalFileStream
     * @param remoteFileName
     * @param transCode
     * @param config
     * @return
     * @throws Exception
     */
    public static boolean uploadFileStream(byte[] lcoalFileStream, String remoteFileName, String transCode, FtpClientConfig config) throws Exception{
        StringBuilder errMsg = new StringBuilder();
        FtpPutStream ftpPutStream = new FtpPutStream(lcoalFileStream, remoteFileName, transCode,true,true, config);
        try {
            if(ftpPutStream.doPutFile()!=null){
                return true;
            }
        } catch (Exception e) {
            errMsg.append(e.getMessage());
        }
        return false;
    }

    /**
     * 本地文件上传到文件传输平台
     * @param localFileName
     * @param remoteFile
     * @param transCode
     * @param config
     * @return
     */
    public static String uploadFile(String localFileName,String remoteFile,String transCode,FtpClientConfig config){
        StringBuilder errMsg = new StringBuilder();
        FtpPut ftpPut = new FtpPut(localFileName,remoteFile,transCode,true,true,config);
        try{
            return ftpPut.doPutFile(timeout,false);
        }catch(Exception e){
            errMsg.append(e.getMessage());
        }
        return null;
    }
}
